<template>
  <div class="chat-container">
    <!-- 聊天历史区域 -->
    <div class="chat-history" ref="chatHistoryRef">
      <!-- 欢迎消息 -->
      <div class="welcome-message">
        <div class="ai-avatar">
          <el-avatar :size="48" src="/src/assets/ai-avatar.svg">
            <el-icon><ChatDotRound /></el-icon>
          </el-avatar>
        </div>
        <div class="welcome-content">
          <h2>您好，我是健康助手</h2>
          <p>我能为您提供健康评估和建议，请告诉我您的问题。</p>
        </div>
      </div>

      <!-- 聊天消息列表 -->
      <div v-for="(message, index) in chatMessages" :key="index" class="message-item" :class="message.role">
        <div class="avatar">
          <el-avatar :size="40" :src="message.role === 'user' ? '/src/assets/user-avatar.svg' : '/src/assets/ai-avatar.svg'">
            <el-icon v-if="message.role === 'user'"><User /></el-icon>
            <el-icon v-else><ChatDotRound /></el-icon>
          </el-avatar>
        </div>
        <div class="message-content">
          <div class="message-text" v-html="formatMessage(message.content)"></div>
          <div v-if="message.role === 'assistant' && message.thinking" class="thinking-indicator">
            <span>思考中</span>
            <span class="dot-animation">...</span>
          </div>
        </div>
      </div>

      <!-- 加载中指示器，仅在没有思考中的消息时显示 -->
      <div v-if="isLoading && !hasThinkingMessage" class="loading-message">
        <div class="avatar">
          <el-avatar :size="40" src="/src/assets/ai-avatar.svg">
            <el-icon><ChatDotRound /></el-icon>
          </el-avatar>
        </div>
        <div class="message-content">
          <div class="thinking-indicator">
            <span>思考中</span>
            <span class="dot-animation">...</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <el-input
        v-model="userInput"
        type="textarea"
        :rows="1"
        placeholder="Message HealthAssist"
        resize="none"
        @keydown.enter.prevent="sendMessage"
        :disabled="isLoading"
        class="message-input"
        :autosize="{ minRows: 1, maxRows: 3 }"
      />
      <div class="input-actions">
        <div class="tool-buttons">
          <el-tooltip content="深度思考" placement="top">
            <el-button circle class="tool-button">
              <el-icon><Cpu /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="搜索" placement="top">
            <el-button circle class="tool-button">
              <el-icon><Search /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="清除记录" placement="top">
            <el-button circle class="tool-button" @click="clearChatHistory">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
        <el-button
          type="primary"
          circle
          @click="sendMessage"
          :disabled="!userInput.trim() || isLoading"
          class="send-button"
        >
          <el-icon><Position /></el-icon>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue'
import { ChatDotRound, User, Position, Cpu, Search, Delete } from '@element-plus/icons-vue'

import { sendMessageToHealthAssistant, type HealthAssistantMessage } from '@/apis/user/userHealthAssistantAPI'
import { parseSSEStream } from '@/utils/sse'
import MarkdownIt from 'markdown-it'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

// 初始化Markdown解析器
const md = new MarkdownIt({
  linkify: true,
  breaks: true,
  typographer: true
})

interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
  thinking?: boolean
}

const userInput = ref('')
const isLoading = ref(false)
const chatHistoryRef = ref<HTMLElement | null>(null)
const authStore = useAuthStore()



// 聊天消息列表
const chatMessages = reactive<ChatMessage[]>([])

// 保存聊天记录到localStorage
const saveChatMessages = () => {
  try {
    // 获取用户ID，如果用户已登录则使用用户ID作为存储键的一部分
    const userId = authStore.userInfo.id || 'guest'
    const storageKey = `health-assistant-messages-${userId}`

    // 过滤掉thinking状态的消息，只保存最终消息
    const messagesToSave = chatMessages.filter(msg => !msg.thinking)

    // 保存到localStorage
    localStorage.setItem(storageKey, JSON.stringify(messagesToSave))
  } catch (error) {
    console.error('保存聊天记录失败:', error)
  }
}

// 从localStorage加载聊天记录
const loadChatMessages = () => {
  try {
    // 获取用户ID，如果用户已登录则使用用户ID作为存储键的一部分
    const userId = authStore.userInfo.id || 'guest'
    const storageKey = `health-assistant-messages-${userId}`

    // 从localStorage获取聊天记录
    const savedMessages = localStorage.getItem(storageKey)
    if (savedMessages) {
      // 解析并加载聊天记录
      const parsedMessages = JSON.parse(savedMessages) as ChatMessage[]

      // 清空当前消息列表并添加保存的消息
      chatMessages.length = 0
      parsedMessages.forEach(message => chatMessages.push(message))
    }
  } catch (error) {
    console.error('加载聊天记录失败:', error)
  }
}

// 清除聊天记录
const clearChatHistory = () => {
  try {
    // 获取用户ID，如果用户已登录则使用用户ID作为存储键的一部分
    const userId = authStore.userInfo.id || 'guest'
    const storageKey = `health-assistant-messages-${userId}`

    // 清空聊天消息数组
    chatMessages.length = 0

    // 从localStorage中删除保存的消息
    localStorage.removeItem(storageKey)

    // 显示成功消息
    ElMessage.success('聊天记录已清除')
  } catch (error) {
    console.error('清除聊天记录失败:', error)
    ElMessage.error('清除聊天记录失败')
  }
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  // 添加用户消息
  chatMessages.push({
    role: 'user',
    content: userInput.value
  })

  // 保存聊天记录
  saveChatMessages()

  // 清空输入框
  const userMessage = userInput.value
  userInput.value = ''

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // 显示加载状态
  isLoading.value = true

  try {
    // 添加AI思考中的消息
    const assistantMessage: ChatMessage = {
      role: 'assistant',
      content: '',
      thinking: true
    }
    chatMessages.push(assistantMessage)

    // 调用健康助手接口
    const stream = await sendMessageToHealthAssistant(userMessage)
    const reader = stream.getReader()

    // 处理流式响应
    await parseSSEStream(
      reader,
      (event) => {
        try {
          // 移除thinking状态
          assistantMessage.thinking = false

          // 处理事件数据 - 直接使用文本内容而不尝试解析JSON
          if (event.data) {
            // 检查是否以data:开头，如果是则直接使用文本内容
            const content = event.data.startsWith('data:') ? event.data.substring(5) : event.data

            // 追加内容
            assistantMessage.content += content

            // 保存聊天记录
            saveChatMessages()

            // 滚动到底部
            nextTick(() => {
              scrollToBottom()
            })
          }
        } catch (error) {
          console.error('解析SSE事件失败:', error)
        }
      },
      () => {
        // 流结束，关闭加载状态
        isLoading.value = false
        scrollToBottom()
        // 保存最终的聊天记录
        saveChatMessages()
      },
      (error) => {
        console.error('流处理错误:', error)
        ElMessage.error('获取响应失败，请稍后再试')
        isLoading.value = false
        // 如果没有收到任何内容，添加错误消息
        if (!assistantMessage.content) {
          assistantMessage.content = '抱歉，我暂时无法回答您的问题。请稍后再试。'
          assistantMessage.thinking = false
          // 保存包含错误消息的聊天记录
          saveChatMessages()
        }
      }
    )
  } catch (error) {
    console.error('Error getting response:', error)
    ElMessage.error('获取响应失败，请稍后再试')
    isLoading.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatHistoryRef.value) {
    chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight
  }
}

// 格式化消息（支持Markdown格式）
const formatMessage = (text: string) => {
  // 使用markdown-it解析Markdown
  return md.render(text)
}

// 计算是否有思考中的消息
const hasThinkingMessage = computed(() => {
  return chatMessages.some(message => message.role === 'assistant' && message.thinking)
})

// 监听消息变化，自动滚动到底部
watch(
  () => chatMessages.length,
  () => nextTick(scrollToBottom)
)

onMounted(() => {
  // 初始化时加载聊天记录
  loadChatMessages()
  // 初始化时滚动到底部
  scrollToBottom()
})
</script>

<style scoped lang="scss">
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: #ededed;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.welcome-message {
  display: flex;
  margin-bottom: 20px;

  .ai-avatar {
    margin-right: 16px;
  }

  .welcome-content {
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      color: #333;
    }

    p {
      margin: 0;
      color: #666;
      font-size: 16px;
    }
  }
}

.message-item {
  display: flex;
  margin-bottom: 16px;

  &.user {
    justify-content: flex-end;
  }

  &.assistant {
    justify-content: flex-start;
  }

  .avatar {
    flex-shrink: 0;
  }

  &.user .avatar {
    margin-left: 12px;
    order: 2;
  }

  &.assistant .avatar {
    margin-right: 12px;
    order: 1;
  }

  .message-content {
    max-width: 70%;
    padding: 12px 16px;
    font-size: 15px;
    line-height: 1.5;

    .message-text {
      white-space: pre-wrap;
    }
  }

  &.user .message-content {
    order: 1;
  }

  &.assistant .message-content {
    order: 2;
  }

  &.user .message-content {
    background-color: #95ec69;
    color: #333;
    border-radius: 10px 0 10px 10px;
    margin-right: 12px;
  }

  &.assistant .message-content {
    background-color: #ffffff;
    color: #333;
    border-radius: 0 10px 10px 10px;
    margin-left: 12px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);

    :deep(p) {
      margin: 0.5em 0;
    }

    :deep(ul), :deep(ol) {
      margin: 0.5em 0;
      padding-left: 1.5em;
    }

    :deep(a) {
      color: #409eff;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }

    :deep(code) {
      background-color: #f5f7fa;
      padding: 0.2em 0.4em;
      border-radius: 3px;
      font-family: monospace;
      font-size: 0.9em;
    }

    :deep(pre) {
      background-color: #f5f7fa;
      padding: 1em;
      border-radius: 5px;
      overflow-x: auto;
      margin: 0.5em 0;

      code {
        background-color: transparent;
        padding: 0;
      }
    }
  }
}

.loading-message {
  display: flex;
  margin-bottom: 16px;
}

.thinking-indicator {
  display: flex;
  align-items: center;
  color: #999;
  font-size: 14px;
  margin-top: 8px;
  margin-left: 12px;

  .dot-animation {
    display: inline-block;
    animation: dotAnimation 1.5s infinite;
    margin-left: 4px;
  }
}

@keyframes dotAnimation {
  0% { opacity: 0.3; }
  50% { opacity: 1; }
  100% { opacity: 0.3; }
}

.input-container {
  margin-top: 16px;
  border-top: 1px solid #eaeaea;
  padding-top: 16px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.message-input {
  flex: 1;
  border-radius: 20px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  :deep(.el-textarea__inner) {
    padding: 12px 16px;
    font-size: 15px;
    resize: none;
    max-height: 120px;
    overflow-y: auto;
    border-radius: 20px;
    border: 1px solid #e0e0e0;
  }
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 12px;
}

.tool-buttons {
  display: flex;
  gap: 8px;
}

.tool-button {
  color: #666;
  background-color: transparent;
  border: none;

  &:hover {
    color: #409eff;
    background-color: #f0f2f5;
  }
}

.send-button {
  font-size: 18px;
  background-color: #07c160;
  border-color: #07c160;

  &:hover, &:focus {
    background-color: #06ad56;
    border-color: #06ad56;
  }
}
</style>
